package com.apples.hexviewer2.adapter;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.apples.hexviewer2.R;
import com.apples.hexviewer2.models.FileData;
import com.apples.hexviewer2.models.OnItemEventListener;
import com.apples.hexviewer2.utils.SysHelper;

import java.util.List;
import java.util.Locale;

public class RecentlyOpenRecyclerAdapter extends RecyclerView.Adapter<HolderRecently> {
    private final List<FileData> mItems;
    private final OnItemEventListener mListener;
    private final SwipeToDeleteCallback mSwipeToDeleteCallback;
    private final Context mContext;

    public RecentlyOpenRecyclerAdapter(final Context context,
                                       final List<FileData> objects,
                                       final OnItemEventListener listener) {
        mContext = context;
        mItems = objects;
        mListener = listener;
        mSwipeToDeleteCallback = new SwipeToDeleteCallback(context);
    }

    /**
     * Returns the SwipeToDeleteCallback.
     *
     * @return SwipeToDeleteCallback
     */
    public SwipeToDeleteCallback getSwipeToDeleteCallback() {
        return mSwipeToDeleteCallback;
    }

    @NonNull
    @Override
    public HolderRecently onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_recently_view, parent, false);
        return new HolderRecently(view);
    }

    @Override
    public void onBindViewHolder(@NonNull HolderRecently viewHolder, int i) {
        if (mItems.isEmpty()) return;
        int idx = i;
        if (idx > mItems.size())
            idx = 0;
        final FileData ud = mItems.get(idx);
        if (ud != null) {
            // Set item views based on the views and data model
            TextView name = viewHolder.getName();
            TextView index = viewHolder.getIndex();
            TextView detail = viewHolder.getDetail();
            if (mListener != null) {
                final View.OnClickListener l = v -> mListener.onClick(ud);
                viewHolder.itemView.setOnClickListener(l);
                final View.OnLongClickListener ll = v -> {
                    mListener.onLongClick(ud);
                    return true;
                };
                viewHolder.itemView.setOnLongClickListener(ll);
            }
            String fmt = "%0" + (String.valueOf(getItemCount()).length() + 1) + "d - ";
            index.setText(String.format(Locale.US, fmt, i + 1));
            name.setText(ud.getName());
            detail.setText(SysHelper.sizeToHuman(mContext, ud.getSize()));
            detail.setTextColor(ContextCompat.getColor(mContext, R.color.textColorHex));
            name.setGravity(SysHelper.isRTL(mContext) ? android.view.Gravity.END : android.view.Gravity.START);
        }
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

    public class SwipeToDeleteCallback extends ItemTouchHelper.SimpleCallback {
        private final ColorDrawable mBackground;


        public SwipeToDeleteCallback(final Context context) {
            super(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
            mBackground = new ColorDrawable(ContextCompat.getColor(context, R.color.colorAccentDisabledHex));
        }


        /**
         * Called by ItemTouchHelper on RecyclerView's onDraw callback.
         *
         * @param c                 The canvas which RecyclerView is drawing its children
         * @param recyclerView      The recycler view.
         * @param viewHolder        The ViewHolder which is being interacted by the User or it was interacted and simply animating to its original position
         * @param dX                The amount of horizontal displacement caused by user's action
         * @param dY                The amount of vertical displacement caused by user's action
         * @param actionState       The type of interaction on the View. Is either ACTION_STATE_DRAG or ACTION_STATE_SWIPE.
         * @param isCurrentlyActive True if this view is currently being controlled by the user or false it is simply animating back to its original state.
         */
        @Override
        public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
            super.onChildDraw(c, recyclerView, viewHolder, dX,
                    dY, actionState, isCurrentlyActive);
            View itemView = viewHolder.itemView;
            int backgroundCornerOffset = 20;

            if (dX > 0) { // Swiping to the right

                mBackground.setBounds(itemView.getLeft(), itemView.getTop(),
                        itemView.getLeft() + ((int) dX) + backgroundCornerOffset,
                        itemView.getBottom());
            } else if (dX < 0) { // Swiping to the left
                mBackground.setBounds(itemView.getRight() + ((int) dX) - backgroundCornerOffset,
                        itemView.getTop(), itemView.getRight(), itemView.getBottom());
            } else { // view is unSwiped
                mBackground.setBounds(0, 0, 0, 0);
            }

            mBackground.draw(c);
        }

        /**
         * Called when ItemTouchHelper wants to move the dragged item from its old position to the new position.
         *
         * @param recyclerView The RecyclerView to which ItemTouchHelper is attached to.
         * @param viewHolder   The ViewHolder which is being dragged by the user.
         * @param target       The ViewHolder over which the currently active item is being dragged.
         * @return True if the viewHolder has been moved to the adapter position of target.
         */
        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
            /* nothing */
            return false;
        }

        /**
         * Called when a ViewHolder is swiped by the user.
         *
         * @param viewHolder The ViewHolder which has been swiped by the user.
         * @param direction  The direction to which the ViewHolder is swiped. It is one of UP, DOWN, LEFT or RIGHT.
         */
        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            final int position = viewHolder.getAdapterPosition();
            FileData ud = mItems.get(position);
            mItems.remove(position);
            notifyItemRemoved(position);
            if (mListener != null)
                mListener.onDelete(ud);
        }
    }
}
